<template>
  <div class="app-container">
    <!-- 标题区域 -->
    <div class="header">
      <h1>生成恒达货代发票</h1>
      <div class="upload-button">
        <el-upload
            class="batch-upload"
            action=""
            :limit="1"
            :auto-upload="false"
            :on-change="handleFileChange"
            accept=".xlsx,.xls"
        >
          <template #trigger>
            <el-button type="primary">选择Excel文件</el-button>
          </template>

          <el-button
              class="ml-3"
              type="success"
              :disabled="!file"
              @click="submitUpload(file)"
          >
            导入数据
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              文件以.xls或.xlsx结尾
            </div>
          </template>
        </el-upload>
        <el-button type="primary" @click="downloadTemplate(staffInfo)">
          <i class="el-icon-download"></i> 下载模板
        </el-button>

        <el-button type="primary" @click="generateInvoice(selectDataList)">
          <i class="el-icon-download"></i> 选中的数据生成货代发票
        </el-button>
      </div>
    </div>
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-input
          v-model.trim="searchKeyword"
          placeholder="请输入FBA搜索"
          clearable
          style="width: 300px;"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch"></el-button>
        </template>
      </el-input>

      <el-input
          v-model.trim="searchSkuKeyword"
          placeholder="请输入产品SKU搜索"
          clearable
          style="width: 300px;"
      >
        <template #append>
          <el-button :icon="Search" @click="handleSearch"></el-button>
        </template>
      </el-input>
    </div>
    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
          :data="currentPageData"
          stripe
          border
          empty-text="暂无数据，请先添加"
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column v-for="key in Object.keys(tableHead.data)"
                         :prop="key"
                         :label="tableHead.data[key]"
                         width="150"
                         sortable >
          <template #default="scope" v-if="Object.keys(tableShowRule).includes(key)">
              <span>
                {{tableShowRule[key][scope.row[key]]}}
              </span>
          </template>
        </el-table-column>


        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
          background
          layout="sizes, prev, pager, next, jumper, ->, total"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          :total="totalItems"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
      />
    </div>


    <!-- 添加/编辑对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
    >
      <el-form
          :model="formData.data"
          :rules="formRules.data"
          ref="formRef"
          label-width="120px"
      >
        <el-form-item
            v-for="key in Object.keys(formData.data)"
            :label="formData.desc[key]"
            :prop="key"
            :key="key"

        >
          <el-input v-if="hengdaInvoiceCheckRule.number.includes(formData.type[key]) && !Object.keys(hengdaInvoiceCheckRule.selected).includes(key)"
                    v-model.trim="formData.data[key]"
                    :placeholder="`请输入${formData.desc[key]}`" :disabled="isEditing && hengdaInvoiceCheckRule.disabled.includes(key)">

          </el-input>
          <el-input v-if="hengdaInvoiceCheckRule.string.includes(formData.type[key]) && !Object.keys(hengdaInvoiceCheckRule.selected).includes(key)"
                    v-model.trim="formData.data[key]" :placeholder="`请输入${formData.desc[key]}`"
                    :disabled="isEditing && hengdaInvoiceCheckRule.disabled.includes(key)">
          </el-input>
          <el-date-picker
              v-if="hengdaInvoiceCheckRule.date.includes(formData.type[key]) && !Object.keys(hengdaInvoiceCheckRule.selected).includes(key)"
              :disabled="isEditing && hengdaInvoiceCheckRule.disabled.includes(key)"
              v-model.trim="formData.data[key]"
              type="date"
              aria-label="建单日期"
              value-format="YYYY-MM-DD"
              placeholder="请选择建单日期"
              style="width: 100%"
          />
          <el-select
              v-if="Object.keys(hengdaInvoiceCheckRule.selected).includes(key)"
              :disabled="isEditing && hengdaInvoiceCheckRule.disabled.includes(key)"
              v-model.trim="formData.data[key]"
              :placeholder="`请选择${formData.desc[key]}`"
          >
            <el-option v-for="sel in hengdaInvoiceCheckRule.selected[key]" :label="sel.label" :value="sel.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
          </span>
      </template>
    </el-dialog>

  </div>

</template>

<script>
import {computed,ref,reactive} from "vue";
import {ElMessage,ElMessageBox} from "element-plus";
import {Search} from "@element-plus/icons-vue";
import generateFormStructure from "@/hooks/common/generateFormStructure";
import {useStore} from "vuex";
import defaultValueRule from "@/hooks/common/defaultValueRule";
import hengdaInvoiceCheckRule from "@/hooks/invoice/hengdaInvoiceCheckRule";
import tableShowRule from "@/hooks/common/tableShowRule";
import {getHengdaInvoiceByStaffId,modifyOrInsertHengdaInvoice, removeHengdaInvoice,submitUpload,downloadTemplate,generateInvoice} from "@/hooks/invoice/HengdaInvoice";

export default {
  name: "HengDaInvoice",
  setup(){
    // 表格数据
    let tableData = reactive({value:[]});
    //获取表格数据
    getHengdaInvoiceByStaffId().then(data=>{
      tableData.value = data||[]
    }).catch(error=>{
      ElMessage.error(error)
    })
    let formData = reactive({data: {},desc: {},type:{}})
    let forwarderFormData = reactive({data: {},desc: {},type:{}})
    let formRules = reactive({data:[]})
    //表头
    let tableHead = reactive({data: {}})

    const file = ref(null);
    //获取表单结构
    generateFormStructure('com.aier.bean.invoice.HengdaInvoice').then(data=>{
      for (let i = 0; i < data.length; i++) {
        Object.keys(data[i]).forEach(key=>{
          formData.data[key] = defaultValueRule[data[i][key][0]]
          formData.desc[key] = data[i][key][1]
          formData.type[key] = data[i][key][0]
          tableHead.data[key] = data[i][key][1]
        })
      }
      //过滤掉不需要填的字段
      for (let key in formData.data){
        if (hengdaInvoiceCheckRule.ignore.includes(key)){
          delete formData.data[key]
          // delete formData.desc[key]
          // delete formData.type[key]
        }
      }

    }).catch(error=>{
      ElMessage.error(error.message)
    })
    // 搜索关键词
    const searchKeyword = ref('');
    // 状态筛选
    const searchSkuKeyword = ref('');
    // 分页相关
    const currentPage = ref(1);
    const pageSize = ref(5);
    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('添加数据');
    const isEditing = ref(false);
    const formRef = ref(null);
    const store = useStore()
    //选择货代相关
    const forwarderVisible = ref(false)

    /** 选中的所有数据列表 **/
    let selectDataList = ref([])


    /** 多选框选中时触发的事件 **/
    const handleSelectionChange = row=>{
      selectDataList.value = [...row]
    }

    // 计算属性 - 筛选和分页后的数据
    const filteredData = computed(() => {
      let result = [...tableData.value];
      // 搜索过滤
      if (searchKeyword.value) {
        const keyword = searchKeyword.value;
        result = result.filter(item =>{
          return item.fbaCode.includes(keyword)
        });
      }
      // sku过滤
      if (searchSkuKeyword.value) {
        const keyword = searchSkuKeyword.value;
        result = result.filter(item => item.sku.includes(keyword));
      }
      return result
    });

    // 处理每页数量变化
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize;
      currentPage.value = 1; // 重置到第一页
    };

    // 计算总条目数
    const totalItems = computed(() => filteredData.value.length);

    // 计算当前页显示的数据
    const currentPageData = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value;
      return filteredData.value.slice(start, start + pageSize.value);
    });




    // 打开编辑对话框
    const openEditDialog = (row) => {
      Object.assign(formData.data, row);
      dialogTitle.value = '编辑数据';
      isEditing.value = true;
      dialogVisible.value = true;
    };



    const staffInfo = store.state.staffInfo
    // 提交表单
    const submitForm = () => {
      formRef.value.validate(valid => {
        if (valid) {
          if (isEditing.value) {
            // 更新数据
            const index = tableData.value.findIndex(item => item.fbaCode === formData.data.fbaCode);
            if (index !== -1) {
              const updateForeignBase = {
                ...formData.data,
                staffId:staffInfo.staffId,
                staffName:staffInfo.staffName
              };
              modifyOrInsertHengdaInvoice(updateForeignBase).then(()=>{
                tableData.value[index] = updateForeignBase
              }).catch(error=>{
                ElMessage.error(error)
              })
            }
          }
          dialogVisible.value = false;
        } else {
          ElMessage.error('请填写完整的表单信息');
          return false;
        }
      });
    };

    // 删除用户
    const handleDelete = (row) => {
      ElMessageBox.confirm(
          `确定要货代发票信息 "${row.fbaCode}" 吗?`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      ).then(() => {

        removeHengdaInvoice({fbaCode:row.fbaCode}).then(()=>{
          tableData.value = tableData.value.filter(item => item.fbaCode !== row.fbaCode);
        }).catch(error=>{
          ElMessage.error(error)
        })
      }).catch(() => {
        // 用户取消操作
      });
    };

    // 处理搜索
    const handleSearch = () => {
      currentPage.value = 1;
    };

    // 处理分页变化
    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    //选择文件变化后回调函数
    const handleFileChange = (uploadFile) => {
      file.value = uploadFile.raw;
    };






    return {
      selectDataList,
      staffInfo,
      handleFileChange,
      submitUpload,
      generateInvoice,
      currentPageData,
      handleSizeChange,
      downloadTemplate,
      file,
      isEditing,
      handleSelectionChange,
      tableData,
      searchKeyword,
      searchSkuKeyword,
      currentPage,
      pageSize,
      dialogVisible,
      dialogTitle,
      formData,
      formRules,
      tableHead,
      formRef,
      filteredData,
      totalItems,
      hengdaInvoiceCheckRule,
      tableShowRule,
      openEditDialog,
      submitForm,
      handleDelete,
      handleSearch,
      handlePageChange,
      forwarderVisible,
      forwarderFormData,
      Search
    };
  },
  components:[Search]
}
</script>

<style scoped>
.app-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 10px;
  height: 100%;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}
.header h1 {
  margin: 0;
  color: #409eff;
  font-weight: 600;
}
.upload-button{
  display: flex;
  gap: 10px;
}

.batch-upload {
  display: flex;
  gap: 10px;
}


.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}
.action-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.table-container {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.status-active {
  color: #67c23a;
  font-weight: 500;
}
.status-inactive {
  color: #f56c6c;
  font-weight: 500;
}
.tag {
  margin-right: 5px;
}
.el-table .warning-row {
  background-color: #fef0f0;
}
.el-table .success-row {
  background-color: #f0f9eb;
}
.footer {
  margin-top: 20px;
  text-align: center;
  color: #909399;
  font-size: 14px;
}
</style>